package network2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

//发送端
public class Talksend implements Runnable {
    private DatagramSocket client;
    private BufferedReader reader;
    private String toIp;//ip
    private int toPort;//端口

    public Talksend(int Port, String toIp, int toPort) {
        try {
            client = new DatagramSocket(Port);
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
        reader = new BufferedReader(new InputStreamReader(System.in));
        this.toIp = toIp;
        this.toPort = toPort;
    }

    @Override
    public void run() {
        while (true) {
            String data;
            try {
                data = reader.readLine();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            byte[] bytes = data.getBytes();
            DatagramPacket packet = new DatagramPacket
                    (bytes, 0, bytes.length, new InetSocketAddress(this.toIp, this.toPort));
            try {
                client.send(packet);
                if (data.equals("bye")) {
                    break;
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        client.close();
    }
}
